// request.js
// const BASE_URL = 'https://jianxiangjinjiren.com'; // 替换为你的API基础URL
const BASE_URL = 'https://www.szchuanxikj.xyz'; // 替换为你的API基础URL
import storage from "./storage";
/**
 * 统一的请求错误处理
 * @param {Object} err - 错误信息
 */
function handleError(err) {
	let message = '请求失败';
	if (err.errMsg) {
		if (err.errMsg.includes('timeout')) {
			message = '请求超时';
		} else if (err.errMsg.includes('fail')) {
			message = '网络错误';
		}
	}
	uni.showToast({
		title: message,
		icon: 'none',
		duration: 2000
	});
	return Promise.reject(err);
}

/**
 * 统一的响应处理
 * @param {Object} res - 响应数据
 */
function handleResponse(res) {
	console.log(res,'请求响应--------------')
	if (res.statusCode === 200) {
		const data = res.data;
		if (data.code === 200) { 
			uni.showToast({
				title: 'success',
				icon: 'none',
				duration: 1000
			});
			return data
		} else {
			
			uni.showToast({
				title: data.message || '请求错误',
				icon: 'none',
				duration: 2000
			});
			
			return Promise.reject(data);
		}
	} else {
		return handleError({
			errMsg: `HTTP错误 ${res.statusCode}`
		});
	}
}

/**
 * 发送请求
 * @param {Object} options - 请求配置
 */
function request(options) {
	// 合并默认配置
	const defaultOptions = {
		url: '',
		method: 'GET',
		data: {},
		header: {
			'Authorization': storage.get('user') ?  'Bearer ' + storage.get('user').token : null,
			
		},
		timeout: 10000
	};

	const mergeOptions = {
		...defaultOptions,
		...options
	};

	// 处理URL
	if (!mergeOptions.url.startsWith('http')) {
		// mergeOptions.url =  mergeOptions.url;
		mergeOptions.url = BASE_URL + mergeOptions.url;
	}

	return new Promise((resolve, reject) => {
		uni.request({
			...mergeOptions,
			success: (res) => {
				resolve(handleResponse(res));
			},
			fail: (err) => {
				reject(handleError(err));
			}
		});
	});
}

// 常用请求方法封装
request.get = (url, data = {}) => request({
	url,
	method: 'GET',
	data
});
request.post = (url, data = {}) => request({
	url,
	method: 'POST',
	data
});
request.put = (url, data = {}) => request({
	url,
	method: 'PUT',
	data
});
request.delete = (url, data = {}) => request({
	url,
	method: 'DELETE',
	data
});

export default request;